package nl.ajonker.railroad.ui.drawcommand;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;

import nl.ajonker.railroad.ui.Orientation;

/**
 * Points:
 * 
 * 
 * A--B--C--D--E<br>
 * \<br>
 * F--G
 * 
 * @author Arjan
 * 
 */
public class SwitchRailCommand extends StraightRailCommand {

	private enum SwitchState {
		STRAIGHT(Color.GREEN), DIVERGING(Color.RED);
		public final Color color;

		private SwitchState(final Color color) {
			this.color = color;
		}
	}

	// private final SwitchState switchState = SwitchState.STRAIGHT;
	private SwitchState switchState = SwitchState.DIVERGING;

	private final int switchSize = dimension / 4;

	private Point a, b, c, d, e, f, g;
	private Point indicator;

	public SwitchRailCommand() {
		super();
	}

	public SwitchRailCommand(final Orientation orientaion) {
		super(orientaion);
	}

	@Override
	protected Point calculatePoints() {
		a = new Point(start);
		b = new Point(a.x + switchSize, a.y);
		c = new Point(b.x + switchSize, b.y);
		d = new Point(c.x + switchSize, c.y);
		e = new Point(d.x + switchSize, d.y);
		f = new Point(c.x + switchSize, c.y + switchSize);
		g = new Point(e.x, f.y);

		indicator = new Point(b.x, b.y - switchSize);
		return e;
	}

	@Override
	public synchronized void drawRail(final Graphics2D g2d) {
		g2d.setStroke(stroke);
		g2d.setColor(railColor);

		draw(g2d, a, e);
		draw(g2d, c, f);
		draw(g2d, f, g);

		if (switchState == SwitchState.STRAIGHT)
			drawStraightActive(g2d);
		else
			drawDivergingActive(g2d);

		rectangle = new Rectangle(b, new Dimension(switchSize, switchSize));
	}

	@Override
	public void onClick() {
		if (switchState == SwitchState.STRAIGHT)
			switchState = SwitchState.DIVERGING;
		else
			switchState = SwitchState.STRAIGHT;
	}

	private void drawDivergingActive(final Graphics2D g2d) {
		g2d.setColor(SwitchState.DIVERGING.color);
		draw(g2d, b, c);
		draw(g2d, c, f);
		drawIndicator(g2d);
	}

	private void drawStraightActive(final Graphics2D g2d) {
		g2d.setColor(SwitchState.STRAIGHT.color);
		draw(g2d, b, d);
		drawIndicator(g2d);
	}

	private void drawIndicator(final Graphics2D g2d) {
		g2d.setStroke(new BasicStroke(1));
		g2d.fillOval(indicator.x, indicator.y, switchSize / 3, switchSize / 3);
	}

}
